package com.huaxin.hxcloud.fragment;

import android.app.Dialog;
import android.content.Context;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.StringUtils;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.ModifyPasswordActivity;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/1/12.
 */

public class ModifyPassword1Fragment extends BaseFragment {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_phone_num)
    TextInputEditText etPhoneNum;
    @BindView(R.id.bt_validate)
    Button btValidate;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_modify_password1;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        etPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) return;
//                Log.d("Zoes",start+","+before+","+count+","+s.length());
                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < s.length(); i++) {
                    if (i != 3 && i != 8 && s.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(s.charAt(i));
                        if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }

                if (!sb.toString().equals(s.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    etPhoneNum.setText(sb.toString());
                    etPhoneNum.setSelection(index);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    public void onResumeView() {
        super.onResumeView();
        ((BaseActivity) getActivity()).setSupportActionBar(toolbar);
    }

    public void ApiVerificationCode(final String phoneNum) {
        final Dialog dialog = DialogUtil.getWaitDialog(getContext(), "发送中...");
        dialog.show();
        Call<BaseDTO> call = getRequestApi().verificationCode2( phoneNum);
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                dialog.dismiss();
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful() && baseDTO != null) {
                    if (baseDTO.isSuccessful()) {
                        ((ModifyPasswordActivity) getActivity()).nextStep(phoneNum);

                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                    }
                } else {
                    ToastUtil.showToast("数据异常");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast("网络故障");
//                ((RegisterActivity) getActivity()).nextStep(phoneNum);
            }
        });
    }


    @OnClick(R.id.bt_validate)
    public void onClick() {
        String phoneNum = etPhoneNum.getText().toString().replaceAll("\\s*", "");
        hideIme();
        if(isMobileNO(phoneNum)){
            ApiVerificationCode(phoneNum);
        }else{
            ToastUtil.showToast("请输入正确的手机号");
        }

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideIme();
    }

    private void hideIme() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm != null && imm.isActive(etPhoneNum)){
            imm.hideSoftInputFromWindow(etPhoneNum.getWindowToken(),0);
        }
    }


    public static boolean isMobileNO(String mobiles) {
        if (StringUtils.isEmpty(mobiles)){
            return false;
        }
        String telRegex = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        return mobiles.matches(telRegex);
    }
}
